package com.group2.comprehensive_treatment.actualpopulation.resident.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.group2.comprehensive_treatment.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * ComprehensiveTreatment
 * com.group2.comprehensive_treatment.actualpopulation.resident.handler
 * 类功能描述
 *
 * @author: August
 * @date: 2025/3/12 19:39
 */

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //获取请求头中令牌

        String token = request.getHeader("token");
        System.out.println(" 拦截器中的 Token 是： " + token);
        try {
            //验证令牌

            JwtUtils.verifyToken(token);
            //验证成功，放⾏请求

            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "⽆效签名 !");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token 过期 !");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token 算法不⼀致 !");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token⽆效 !!");
        }
        //设置状态

        map.put("state", false);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        //相应json 数据

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
